from django.views import View
from django import http
from django_redis import get_redis_connection
from apps.verifications.libs.captcha import captcha
from celery_tasks.yuntongxun.ccp_sms import CCP
import logging
import random
from celery_tasks.sms.tasks import ccp_send_sms_code
logger = logging.getLogger('django')
# Create your views here.
#关于短信验证码/sms_codes/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(View):
    '''短信验证码'''
    def get(self, request, mobile):
        #验证用户是否重复使用手机验证
        redis_counts = get_redis_connection('verify_code')

        num = redis_counts.get('user_%s'% mobile)
        print(num)

        if not num is None:
            return http.JsonResponse({'code':400,
                                      'errmsg':'重复使用手机验证码'})


        #拿到uuid和客户端输入的图形验证码数据
        uuid = request.GET.get('image_code_id')
        image_code_client = request.GET.get('image_code')

        #获取数据比对redis中的图片验证码
        redis_count = get_redis_connection('verify_code')

        image_code_server = redis_count.get('img_%s' % uuid)
        print(image_code_server)
        if not image_code_server:
            return http.JsonResponse({'code': 400,
                                      'errmsg':'验证码已失效'})
        #防止恶意使用图片验证码要把验证码删掉
        try:
            redis_count.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)

        image_code_server = image_code_server.decode()
        print(image_code_server)
        #比对用户输入的验证码和redis的验证码(注意：从redis取出的是二进制数据)
        if image_code_server.lower() != image_code_client.lower():
            return http.JsonResponse({'code': 400,
                                      'errmsg':'验证码输入不正确'})
        #代码执行到此说明图片验证码验证成功我们向用户发送验证码并把生成的验证码存入数据库
        #生成一个随机六位数
        mun_code = '%06d'% random.randint(1, 999999)
        logger.info(mun_code)
        #保存验证码
        ps = redis_count.pipeline()
        ps.setex('sms_%s'% mobile, 300, mun_code)
        #给此用户手机号做标记目的是防止恶意攻击
        ps.setex('user_%s'% mobile, 300, 1)

        ps.execute()
        #发送短信
        try:
            #CCP().send_template_sms(mobile, [mun_code, 5], 1)
            #调用异步任务发短信
            ccp_send_sms_code.delay(mobile, mun_code)
            return http.JsonResponse({'code':0,
                                      'errmsg':'发送成功'})

        except Exception as e:
            logger.error(e)


#图片验证码
class ImageCodeView(View):
    '''返回图片验证码'''
    def get(self, request, uuid):
        '''将验证码传到redis并返回'''

        #生成验证码
        text, image = captcha.captcha.generate_captcha()
        #创建redis链接对象
        redis_count = get_redis_connection('verify_code')
        #利用redis链接对象将验证码保存到redis
        redis_count.setex('img_%s' % uuid, 300, text)
        #返回图片
        return http.HttpResponse(image, content_type='image/jpg')